//
// Created by wenda.zhao on 2023/2/27.
//
#include <jni.h>
#include <string>
#include <iostream>
#include <functional>
#include <memory>
#include <unistd.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include <gui/SurfaceComposerClient.h>

#include "android/log.h"

#include "SequenceRecorder.h"

#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,"DisplayRecorder",__VA_ARGS__)


JNIEnv *mEnv;
jobject recordListener;
SequenceRecorder* mSequenceRecorder;

void onStartOne(const char *fileName) {
    LOGD("onStartOne %s", fileName);
    if (mEnv != nullptr && recordListener != nullptr) {
        jclass clazz = mEnv->GetObjectClass(recordListener);
        jmethodID jmid = mEnv->GetMethodID(clazz, "onStart", "(Ljava/lang/String;)V");
        mEnv->CallVoidMethod(recordListener, jmid, mEnv->NewStringUTF(fileName));
    }
}

void onFinishOne() {
}

void onFail(int errCode) {
    LOGD("onFail %d", errCode);
    if (mEnv != nullptr && recordListener != nullptr) {
        jclass clazz = mEnv->GetObjectClass(recordListener);
        jmethodID jmid = mEnv->GetMethodID(clazz, "onError", "(I)V");
        mEnv->CallVoidMethod(recordListener, jmid, errCode);
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_ecarx_jni_recorder_ScreenRecorder_nativeStart(JNIEnv *env, jobject thiz, jstring root_path,
                                                   jint duration, jobject recorder_listener) {

    mEnv = env;
    recordListener = recorder_listener;

    std::optional<android::PhysicalDisplayId> defaultDisplayId = android::SurfaceComposerClient::getInternalDisplayId();
    android::PhysicalDisplayId displayId = *defaultDisplayId;

    const char *rootPath = env->GetStringUTFChars(root_path, nullptr);
    LOGD("ScreenRecorder_nativeStart rootPath=%s duration=%d", rootPath, duration);
    auto *sequenceRecorder = new SequenceRecorder(displayId, rootPath, duration);
    sequenceRecorder->setCallback(
            [](char const *fileName) { onStartOne(fileName); },
            []() { onFinishOne(); },
            [](int errCode) { onFail(errCode); }
    );
    mSequenceRecorder = sequenceRecorder;
    sequenceRecorder->start();

    env->ReleaseStringUTFChars(root_path, rootPath);

}

extern "C"
JNIEXPORT void JNICALL
Java_ecarx_jni_recorder_ScreenRecorder_nativeStop(JNIEnv *env, jobject thiz) {
    if(mSequenceRecorder != nullptr){
	mSequenceRecorder->stop();
    }
}
